// 文件路径: com/sadam/ui4/FragmentSelfPage/FragmentComposition/FragmentComposition.java
package com.sadam.ui4.FragmentSelfPage.FragmentComposition;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sadam.ui4.ActivityLogin;
import com.sadam.ui4.Data.MySqLiteOpenHelper;
import com.sadam.ui4.Data.User;
import com.sadam.ui4.Data.Video;
import com.sadam.ui4.FragmentSelfPage.FragmentEditVideo;
import com.sadam.ui4.FragmentSelfPage.FragmentPersonalVideoPlayer;
import com.sadam.ui4.FragmentSelfPage.FragmentSelfPage;
import com.sadam.ui4.MainActivity;
import com.sadam.ui4.R;

import java.util.ArrayList;
import java.util.List;

public class FragmentComposition extends Fragment {

    private RecyclerView recyclerView;
    private VideoAdapter adapter;
    private List<Video> videoList = new ArrayList<>();
    private MySqLiteOpenHelper dbHelper;
    private boolean isLoading = false;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (getActivity() instanceof MainActivity) {
            dbHelper = ((MainActivity) getActivity()).getMySqLiteOpenHelper();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_composition, container, false);

        recyclerView = view.findViewById(R.id.recycler_view_videos);
        if (recyclerView == null) {
            Log.e("FragmentComposition", "RecyclerView ID 可能错误");
            return view;
        }

        adapter = new VideoAdapter(videoList, requireContext());

        // 设置点击事件
        adapter.setOnVideoClickListener((video, position) -> {
            openVideoPlayer(video, position);
        });

        // 新增：设置长按事件
        adapter.setOnVideoLongClickListener((video, position) -> {
            showVideoActionDialog(video, position);

        });

        recyclerView.setLayoutManager(new GridLayoutManager(requireContext(), 2));
        recyclerView.setAdapter(adapter);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        loadUserVideos();
    }

    /**
     * 优化加载方法 - 添加防重复加载
     */
    public void loadUserVideos() {
        if (!isAdded() || isLoading || dbHelper == null) return;

        // 检查是否正在加载
        if (isLoading) {
            Log.d("FragmentComposition", "正在加载中，跳过重复请求");
            return;
        }

        isLoading = true;

        User currentUser = ActivityLogin.getCurrentUserFromSharedPrefrences(requireContext(), dbHelper);
        if (currentUser == null) {
            videoList.clear();
            requireActivity().runOnUiThread(() -> adapter.notifyDataSetChanged());
            isLoading = false;
            return;
        }

        new Thread(() -> {
            try {
                // 模拟网络延迟，让用户感知到加载过程
                Thread.sleep(100);

                List<Video> videos = dbHelper.getAllVideosByUser(currentUser);
                requireActivity().runOnUiThread(() -> {
                    videoList.clear();
                    videoList.addAll(videos);
                    adapter.notifyDataSetChanged();
                    isLoading = false;
                    Log.d("FragmentComposition", "作品数据加载完成，数量: " + videos.size());
                });
            } catch (Exception e) {
                e.printStackTrace();
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(getContext(), "加载失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    isLoading = false;
                });
            }
        }).start();
    }

    /**
     * 打开视频播放器
     */
    private void openVideoPlayer(Video video, int position) {
        if (videoList.isEmpty()) {
            Toast.makeText(requireContext(), "暂无视频可播放", Toast.LENGTH_SHORT).show();
            return;
        }
        // 使用默认设置（启用滑动）或者明确启用滑动
        FragmentPersonalVideoPlayer player = FragmentPersonalVideoPlayer.newInstance(videoList, position, true);
        // 或者使用原有的两个参数方法（保持向后兼容）
        // FragmentPersonalVideoPlayer player = FragmentPersonalVideoPlayer.newInstance(videoList, position);
        if (getActivity() != null) {
            player.show(getActivity().getSupportFragmentManager(), "personal_video_player");
        }
    }

    /**
     * 显示作品操作对话框（删除/编辑）
     */
    public void showVideoActionDialog(Video video, int position) {
        String[] options = {"删除作品", "编辑作品"};

        new AlertDialog.Builder(requireContext())
                .setTitle("作品操作")
                .setItems(options, (dialog, which) -> {
                    switch (which) {
                        case 0: // 删除
                            showDeleteConfirmDialog(video, position);
                            break;
                        case 1: // 编辑
                            openEditVideoDialog(video);
                            break;
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 显示删除确认对话框
     */
    private void showDeleteConfirmDialog(Video video, int position) {
        new AlertDialog.Builder(requireContext())
                .setTitle("确认删除")
                .setMessage("确定要删除这个作品吗？此操作不可恢复。")
                .setPositiveButton("删除", (dialog, which) -> {
                    deleteVideo(video, position);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 删除作品
     */
    private void deleteVideo(Video video, int position) {
        new Thread(() -> {
            try {
                boolean success = dbHelper.deleteVideo(video.getId());
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        if (success) {
                            // 从列表中移除
                            if (position < videoList.size()) {
                                videoList.remove(position);
                                adapter.notifyItemRemoved(position);
                                if (position < videoList.size()) {
                                    adapter.notifyItemRangeChanged(position, videoList.size() - position);
                                }
                            }

                            Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();

                            // 通知主页刷新
                            if (getActivity() instanceof MainActivity) {
                                ((MainActivity) getActivity()).refreshHomePage();
                            }

                            // 刷新获赞数
                            refreshUserLikesCount();

                        } else {
                            Toast.makeText(getContext(), "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() ->
                            Toast.makeText(getContext(), "删除失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
                }
            }
        }).start();
    }

    /**
     * 打开编辑作品对话框
     */
    private void openEditVideoDialog(Video video) {
        FragmentEditVideo editDialog = FragmentEditVideo.newInstance(video.getId());

        // 设置编辑完成后的回调
        editDialog.setOnVideoUpdatedListener(() -> {
            // 刷新作品列表
            loadUserVideos();

            // 刷新获赞数
            refreshUserLikesCount();

            // 通知主页刷新
            if (getActivity() instanceof MainActivity) {
                ((MainActivity) getActivity()).refreshHomePage();
            }

            Toast.makeText(getContext(), "作品信息已更新", Toast.LENGTH_SHORT).show();
        });

        editDialog.show(getParentFragmentManager(), "edit_video");
    }

    /**
     * 刷新用户获赞数
     */
    private void refreshUserLikesCount() {
        User currentUser = ActivityLogin.getCurrentUserFromSharedPrefrences(
                getContext(),
                dbHelper
        );
        if (currentUser != null) {
            // 通知父Fragment刷新获赞数
            Fragment parentFragment = getParentFragment();
            if (parentFragment instanceof FragmentSelfPage) {
                ((FragmentSelfPage) parentFragment).refreshUserLikesCount(currentUser.getId());
            }
        }
    }
}